package com.jweb.framework.core.config;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

import com.jweb.framework.core.impl.DefaultActionHolder;


public class ActionParser {
	
	private static ActionParser actionParser = new ActionParser() ;
	
	protected static Collection<BeanDefinition> createActions(Element element , ParserContext parserContext) {
		
		List list = DomUtils.getChildElementsByTagName(element , "jservice");
		ManagedList managedList = new ManagedList();
		for(Iterator it = list.iterator() ; it.hasNext() ; ){
			Element ele = (Element) it.next();
			managedList.add(actionParser.doParse(ele , parserContext));
		}
		
		return managedList ;
	}
	
	protected Object doParse(Element ele , ParserContext parserContext) {
		
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(DefaultActionHolder.class);
		String ref = ele.getAttribute("ref");
		
		if(StringUtils.hasText(ref)){
			beanDefinitionBuilder.addConstructorArgReference(ref);
		}
		else {
			String clazz = ele.getAttribute("class");
			if(StringUtils.hasText(clazz)){
				BeanDefinitionHolder bHolder = parserContext.getDelegate().parseBeanDefinitionElement(ele , beanDefinitionBuilder.getRawBeanDefinition());
				if(bHolder != null){
					bHolder = parserContext.getDelegate().decorateBeanDefinitionIfRequired(ele , bHolder , beanDefinitionBuilder.getRawBeanDefinition());
				}
				else {
					parserContext.getReaderContext().error("cannot builder jservice ", ele);
				}
				
				beanDefinitionBuilder.addConstructorArgValue(bHolder);
			}
			else {
				String placeHolder = ele.getAttribute("place-holder");
				if(StringUtils.hasText(placeHolder) && "true".equals(placeHolder)){
					beanDefinitionBuilder.addConstructorArgValue(Boolean.valueOf(true));
				}
				else {
					beanDefinitionBuilder.addConstructorArgValue(Boolean.valueOf(false));
				}
			}
		}
		
		String id = ele.getAttribute("id");
		beanDefinitionBuilder.addConstructorArgValue(id);
		
		String throwNoSuchMethodException = ele.getAttribute("throwNoSuchMethodException");
		if(!StringUtils.hasText(throwNoSuchMethodException)){
			throwNoSuchMethodException = "false";
		}
		beanDefinitionBuilder.addConstructorArgValue(throwNoSuchMethodException);
		
		String operations = ele.getAttribute("operations");
		if(StringUtils.hasText(operations)){
			beanDefinitionBuilder.addPropertyValue("operations", operations);
		}
		
		return beanDefinitionBuilder.getBeanDefinition() ;
	}
	
}
